package com.zyh.websocket.service;

import com.zyh.counselor.service.ICounselorService;
import com.zyh.websocket.constant.MessageConstant;
import com.zyh.websocket.entity.Message;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class MessageSenderService {
    private final SimpMessagingTemplate messagingTemplate;
    private final ICounselorService counselorService;

    // 发送私聊消息
    public void sendPrivateMessage(Message message) {
        String destination = resolveChatRoute(message);
        sendMessage(destination, message, String.valueOf(message.getReceiverId()));
        log.info("私聊消息已发送：{} → {}。路径是->{}", message.getSenderId(), message.getReceiverId(), destination);
    }

    // 发送预约请求（用户→咨询师）
    public void sendAppointmentRequest(Message message) {
        sendMessage(
                MessageConstant.Route.COUNSELOR_APPOINTMENT_QUEUE,
                message,
                String.valueOf(message.getReceiverId()) // 咨询师ID
        );
        log.info("预约请求已发送至咨询师：{}", message.getReceiverId());
    }

    // 发送预约请求（咨询师→用户）
    public void sendAppointmentResult(Message message) {
        sendMessage(
                MessageConstant.Route.USER_APPOINTMENT_RESULT_QUEUE,
                message,
                String.valueOf(message.getReceiverId())
        );
        log.info("预约结果已发送至用户：{}", message.getReceiverId());
    }

    // 发送审批请求（→管理员）
    public void sendApprovalRequest(String targetUserId, Message message) {
        sendMessage(
                MessageConstant.Route.ADMIN_APPROVAL_QUEUE,
                message,
                targetUserId
        );
        log.info("审批请求已发送至管理员: {}", targetUserId);
    }

    // 发送审批结果（管理员→用户）
    public void sendApprovalResult(Message message) {
        sendMessage(
                MessageConstant.Route.USER_APPROVAL_RESULT_QUEUE,
                message,
                String.valueOf(message.getReceiverId())
        );
        log.info("审批结果已发送至：{}", message.getReceiverId());
    }

    // 系统广播
    public void broadcastSystemMessage(Message message) {
        sendMessage(MessageConstant.Route.SYSTEM_TOPIC, message, null);
        log.info("系统广播：{}", message.getContent());
    }

    private String resolveChatRoute(Message message) {
        return MessageConstant.Route.USER_CONSULTATION_QUEUE;
    }

    private void sendMessage(String destination, Message message, String userId) {
        try {
            if (userId != null) {
                messagingTemplate.convertAndSendToUser(userId, destination, message);
                log.debug("发送用户专属消息 [{}] → /user-->{}-->{}", userId, userId, destination);
            } else {
                messagingTemplate.convertAndSend(destination, message);
                log.debug("发送广播消息 [{}]", destination);
            }
        } catch (Exception e) {
            log.error("消息发送失败 [{}]：{}", destination, e.getMessage());
            throw new RuntimeException("消息发送失败", e);
        }
    }
}